import React, {Component} from "react";
import {Button, Col, DatePicker, Form, Input, Row, Select, message, InputNumber, Divider, Collapse} from "antd";
import moment from 'moment';
import {API_URL} from "../constants";
import ContractTable from "../utilComponent/Table";
import {getOptions, isBlank} from "../util/util";
import dayjs from "dayjs";
import '../styles.css'; // 引入CSS文件
import {ArrowUpOutlined} from '@ant-design/icons';

const dateFormat = 'YYYY-MM-DD';

const ZOHO = window.ZOHO;
const {TextArea} = Input;

class contractForm extends Component {

    constructor(props) {

        super(props);
        this.contractTableRef = React.createRef();
        this.formRef = React.createRef();

        this.state = {
            // 客户
            accountOptions: [],
            // 抬头
            shipperInformationOptions: [],
            // 国家
            countryOptions: [],
            // 币种
            CurrencyOptions: [],
            // 目的港
            DestinationPortOptions: [],
            // 起运港
            LoadingPortOptions: [],
            paddedNumber: 0,
        };
    }

    async componentDidMount() {
        const {current} = this.formRef;

        let shipperOptions = [];
        let accountOptions = [];
        let countryOptions = [];
        let CurrencyOptions = [];
        // 目的港
        let DestinationPortOptions = [];
        // 起运港
        let LoadingPortOptions = [];
        try {
            let ShipperInformations = await getOptions("ShipperInformation");
            shipperOptions = ShipperInformations.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let accounts = await getOptions("Accounts");
            accountOptions = accounts.map(item => ({
                value: item.id,
                label: item.Account_Name,
            }));
            let countrys = await getOptions("States");
            countryOptions = countrys.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let Currencytypes = await getOptions("Currencytype");
            CurrencyOptions = Currencytypes.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let PortInformations = await getOptions("PortInformation", "id,Name,PortType");
            PortInformations.map(item => {
                if (item.PortType === "目的港") {
                    DestinationPortOptions.push({
                        value: item.id,
                        label: item.Name,
                    })
                }
                if (item.PortType === "装运港") {
                    LoadingPortOptions.push({
                        value: item.id,
                        label: item.Name,
                    })
                }

            });
        } catch (error) {
            console.error(error);
        }
        current.setFieldValue('ContractDate', dayjs(moment().format(dateFormat), 'YYYY-MM-DD'));
        current.setFieldValue('OverShort_Shipment', 5);
        current.setFieldValue('ContractType', '外销合同');
        current.setFieldValue('TransactionMethod', 'FOB');

        if (window.id !== undefined) {
            try {
                const data = await ZOHO.CRM.API.getRecord({
                    Entity: "Foreignsacontract",
                    approved: "both",
                    RecordID: window.id,
                });
                const formdata = data.data[0];
                console.log(formdata);
                formdata.DeliveryDate = isBlank(formdata.DeliveryDate) ? undefined : moment(formdata.DeliveryDate);
                formdata.ContractDate = isBlank(formdata.ContractDate) ? undefined : moment(formdata.ContractDate);
                formdata.EstimatedShippingDate = isBlank(formdata.EstimatedShippingDate) ? undefined : moment(formdata.EstimatedShippingDate);
                formdata.Header = {
                    value: formdata.Header?.id,
                    label: formdata.Header?.name,
                };
                formdata.Account = {
                    value: formdata.Account?.id,
                    label: formdata.Account?.name,
                }
                formdata.TradingCountry = {
                    value: formdata.TradingCountry?.id,
                    label: formdata.TradingCountry?.name,
                }
                formdata.Currencys = {
                    value: formdata.Currencys?.id,
                    label: formdata.Currencys?.name,
                };
                formdata.DestinationPort = {
                    value: formdata.DestinationPort?.id,
                    label: formdata.DestinationPort?.name,
                }
                formdata.ShippingPort = {
                    value: formdata.ShippingPort?.id,
                    label: formdata.ShippingPort?.name,
                }
                current.setFieldsValue(formdata);

            } catch (error) {
                console.error(error);
            }
        }
        this.setState({ // 客户
            accountOptions: accountOptions,
            shipperInformationOptions: shipperOptions,
            countryOptions: countryOptions,
            CurrencyOptions: CurrencyOptions,
            DestinationPortOptions: DestinationPortOptions,
            LoadingPortOptions: LoadingPortOptions,
        });
    }

    changeAccount = async (value) => {
        const {current} = this.formRef;
        current.setFieldValue("Account", {
            value: value.key,
            label: value.label
        })
        ZOHO.CRM.API.getRecord({
            Entity: "Accounts", approved: "both", RecordID: value.key
        }).then(data => {
            this.changeCompanyletterhead({
                key: data.data[0].CompanyHead?.id,
                label: data.data[0].CompanyHead?.name
            })
            this.changeCurrency({
                key: data.data[0].Currencys?.id,
                label: data.data[0].Currencys?.name
            })
            current.setFieldValue("DestinationPort", {
                value: data.data[0].DestinationPort?.id,
                label: data.data[0].DestinationPort?.name
            })
            current.setFieldValue("ShippingPort", {
                value: data.data[0].LoadingPort?.id,
                label: data.data[0].LoadingPort?.name
            })
            current.setFieldValue("TradingCountry", {
                value: data.data[0].CountryCode?.id,
                label: data.data[0].CountryCode?.name
            })

            current.setFieldValue("PayTerms", data.data[0].PaymentMethod)
            current.setFieldValue("PayMethod", data.data[0].PaymentMethod)
            current.setFieldValue("Post_Contractual_Terms", data.data[0].Subsequentterms)
        })
    }
    changeCompanyletterhead = (value) => {
        const {current} = this.formRef;
        let {paddedNumber} = this.state;
        current.setFieldValue("Header", {
            value: value.key,
            label: value.label
        })
        if (isBlank(value.key)) {
            return;
        }
        ZOHO.CRM.API.getRecord({
            Entity: "ShipperInformation", approved: "both", RecordID: value.key
        }).then(async (data) => {
            current.setFieldValue("ShipperInformationName", data.data[0].China_Name)
            if (isBlank(window.id)) {
                let func_name = "serialnumber";
                let req_data = {
                    "arguments": JSON.stringify({
                        "id": "185647000001230419",
                        "count": 1
                    })
                };
                if (paddedNumber === 0) {
                    await ZOHO.CRM.FUNCTIONS.execute(func_name, req_data)
                        .then(function (data) {
                            paddedNumber = data.details.output.toString().padStart(4, '0');
                        })
                    this.setState({paddedNumber: paddedNumber}, () => {
                        // 在回调函数中执行其他操作
                    });
                }
                let code = `I${value.label}${moment().format('YYYYMM')}${paddedNumber}`;
                console.log(code)
                current.setFieldValue("Name", code)
            }

        })
    }
    changeCountry = (value) => {
        const {current} = this.formRef;
        current.setFieldValue("TradingCountry", {
            value: value.key,
            label: value.label
        })
    }
    handleCancel = () => {
        const {current} = this.formRef;
        current.resetFields();
    };
    changeCurrency = (value) => {
        const {current} = this.formRef;

        if (value === undefined) {
            current.setFieldValue("Currencys", {
                value: '',
                label: ''
            })
        } else {
            current.setFieldValue("Currencys", {
                value: value.key,
                label: value.label
            })
        }
    }
    changePort = (fieldname, value) => {
        if (value !== undefined) {
            const {current} = this.formRef;
            current.setFieldValue(fieldname, {
                value: value.key,
                label: value.label
            })
        }

    }

    getRate = () => {
        return 1;
    }
    scrollToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth"  // 使用平滑滚动效果
        });
    }
    updateTotal = (sumData) => {
        const {current} = this.formRef;
        console.log(sumData)
        Object.entries(sumData)?.map(([key, value]) => {
            current.setFieldValue(key, Number(value).toFixed(4))
        })
    }

    render() {
        const {
            accountOptions,
            countryOptions,
            shipperInformationOptions,
            CurrencyOptions,
            LoadingPortOptions,
            DestinationPortOptions
        } = this.state;
        const {Item} = Form;

        return (
            <div>
                <Form ref={this.formRef}>
                    <Collapse size="middle" defaultActiveKey={[1, 2, 3, 4]}>
                        <Collapse.Panel key="1" header="合同信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="预计船期" name="EstimatedShippingDate">
                                        <DatePicker className="input-field" format={dateFormat}/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="交货日期" name="DeliveryDate">
                                        <DatePicker className="input-field" format={dateFormat}/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="客户订单号" name="AccountOrderNo">
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="合同品名" name="ContractItem">
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="合同日期" name="ContractDate">
                                        <DatePicker className="input-field"
                                                    defaultValue={dayjs(moment().format(dateFormat), 'YYYY-MM-DD')}
                                                    format={dateFormat}/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="合同类型" name="ContractType">
                                        <Select className="input-field">
                                            <Select.Option value="外销合同">外销合同</Select.Option>
                                            <Select.Option value="内销合同">内销合同</Select.Option>
                                        </Select>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="溢短装" name="OverShort_Shipment">
                                        <InputNumber className="input-field" step={0.1}/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="折扣" name="Discount">
                                        <InputNumber className="input-field" step={0.1}/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="成交方式" name="TransactionMethod">
                                        <Input className="input-field"/>
                                    </Item>
                                    <Item label="" name="Name" hidden={true}>
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                        <Collapse.Panel key="2" header="客户信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="客户" name="Account" labelAlign="right"
                                          rules={[{required: true, message: '请选择客户'}]}>
                                        <Select
                                            labelInValue
                                            className="input-field"
                                            showSearch
                                            onChange={this.changeAccount}
                                            options={accountOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="币种" name="Currencys">
                                        <Select
                                            className="input-field"
                                            allowClear
                                            labelInValue
                                            showSearch
                                            onChange={this.changeCurrency}
                                            options={CurrencyOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="发货人代码" name="Header" labelAlign="right">
                                        <Select
                                            labelInValue
                                            className="input-field"
                                            showSearch
                                            onChange={this.changeCompanyletterhead}
                                            options={shipperInformationOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="发货人名称" name="ShipperInformationName">
                                        <Input className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="装运港" name="ShippingPort">
                                        <Select
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={value => {
                                                this.changePort('LoadingPort', value)
                                            }}
                                            options={LoadingPortOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="目的港" name="DestinationPort">
                                        <Select
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={value => {
                                                this.changePort('DestinationPort', value)
                                            }}
                                            options={DestinationPortOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>

                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="贸易地区" name="TradingRegion">
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="贸易国家" name="TradingCountry">
                                        <Select
                                            labelInValue
                                            className="input-field"
                                            showSearch
                                            onChange={this.changeCountry}
                                            options={countryOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="付款方式" name="PayMethod">
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                            </Row>

                        </Collapse.Panel>
                        <Collapse.Panel key="3" header="条款信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={16}>
                                    <Item label="付款条款" name="PayTerms">
                                        <TextArea className="input-field" rows={4}/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={16}>
                                    <Item label="合同后置条款" name="Post_Contractual_Terms">
                                        <TextArea className="input-field" rows={4}/>
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                        <Collapse.Panel key="4" header="合计信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={8}>
                                    <Item label="合计数量" name="Quantity">
                                        <InputNumber step={0.0001} className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                                <Col span={8}>
                                    <Item label="合计箱数" name="QuantityperCarton">
                                        <InputNumber step={0.0001} className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                                <Col span={8}>
                                    <Item label="合计金额" name="TotalAmount">
                                        <InputNumber step={0.0001} className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={8}>
                                    <Item label="合计毛重" name="TotalGrossWeight">
                                        <InputNumber step={0.0001} className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                                <Col span={8}>
                                    <Item label="合计净重" name="TotalNetWeight">
                                        <InputNumber step={0.0001} className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                                <Col span={8}>
                                    <Item label="合计体积" name="TotalVolume">
                                        <InputNumber step={0.0001} className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                    </Collapse>
                </Form>

            </div>

        );
    }
}

export default contractForm;